package org.aiforum.backend.service;

import org.aiforum.backend.common.CacheContext;
import org.aiforum.backend.common.Response;
import org.aiforum.util.ImageUtil;
import org.springframework.stereotype.Service;

import verification.VerificationCode;
import verification.VerrficationCodeFactory;

/**
 * 验证码业务实现类
 * @author Administrator
 *
 */
@Service("verificationCodeService")
public class VerificationCodeServiceImpl implements VerificationCodeService{

	@Override
	public Response getVerificationCode(int height, int width) {
		Response response=Response.getInstaner();
		response.setState(true);
		//生成验证码
		VerificationCode verificationCode=VerrficationCodeFactory.generateVerifictionCode(width, height);
		//缓存验证码三分钟
		long timeout=1000*60*3;
		CacheContext.setCache(verificationCode.getCode(), verificationCode.getCode(), timeout);
		verificationCode.setCode(ImageUtil.encodeToBase64(verificationCode.getImage()));
		verificationCode.setImage(null);
		response.setData(verificationCode);
		return response;
	}

	@Override
	public Response checkVerificaionCode(String code) {
		Response response=Response.getInstaner();
		if(CacheContext.containsCache(code)){
			response.setState(true);
		}else{
			response.setMessage("verificationCode code error");
		}
		return response;
	}

	@Override
	public boolean removeVerificationCode(String code) {
		if(CacheContext.containsCache(code)){
			CacheContext.delCache(code);
			return true;
		}else{
			return false;
		}
	}

}
